<!-- 优惠卷管理 -->
<template>
  <div>
    <!-- 查找 -->
    <div>
      <el-space wrap>
        <el-input v-model.trim="databinding.title" placeholder="请输入优惠卷名称" />
        <el-select v-model="databinding.type" class="m-2" placeholder="请选择优惠卷的类型">
          <el-option v-for="item in couponTypeMap" :key="item.value" :label="item.name" :value="item.value" />
        </el-select>
        <el-select v-model="databinding.status" class="m-2" placeholder="请选择优惠卷状态">
          <el-option v-for="item in couponStatusMap" :key="item.value" :label="item.name" :value="item.value" />
        </el-select>
        <el-button type="primary" :icon="Search" @click="couponsearch">查找</el-button>
        <el-button type="primary" :icon="Plus" @click="offeraddition" v-permission='"promotion:coupon:create"'>添加</el-button>
        <el-button type="primary" :icon="Download" @click="exportClick()">当前页导出</el-button>
      </el-space>
    </div>

    <!-- 优惠卷表格 -->
    <div style="margin-top: 25px;">
      <el-table :data="tabledata.list" border style="width:100%" id="table">
        <el-table-column prop="id" label="优惠卷ID" align="center" width="110px" />
        <el-table-column prop="title" label="优惠卷名称" align="center" width="110px" />
        <el-table-column prop="type" label="优惠卷类型" align="center" width="110px">
          <template #default="scope">{{scope.row.type == 1 ?'满减卷':'立减卷'}}</template>
        </el-table-column>
        <el-table-column prop="description" label="介绍" align="center" width="110px" />
        <el-table-column prop="total" label="优惠卷数量" align="center" width="110px" />
        <el-table-column prop="surplus" label="剩余数量" align="center" width="110px" />
        <el-table-column prop="limit" label="每人限领" align="center" width="110px" />
        <el-table-column prop="discount" label="满减金额" align="center" width="110px">
          <template #default="scope">减免{{scope.row.discount}}</template>
        </el-table-column>
        <el-table-column prop="min" label="最低消费" align="center" width="110px">
          <template #default="scope">满{{scope.row.discount}}元可用</template>
        </el-table-column>
        <el-table-column prop="status" label="状态" align="center" width="110px">
          <template #default="scope">
            <el-tag class="ml-2" :type="scope.row.status == 0?'warning':(scope.row.gmtEnd <  Date.now() ?'danger':'')">
              {{scope.row.status == 0?'下架':(scope.row.gmtEnd < Date.now() ?'已过期':'正常')}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="categoryTitle" label="使用类目名称" align="center" width="110px">
          <template #default="scope">
            <el-tag>{{scope.row.categoryTitle?scope.row.categoryTitle:'全部类目'}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="categoryId" label="使用类目ID" align="center" width="110px" />
        <el-table-column prop="days" label="领卷相对天数" align="center" width="110px">
          <template #default="scope">{{scope.row.days?scope.row.days:'无'}}</template>
        </el-table-column>
        <el-table-column prop="gmtStart" label="领卷开始时间" align="center" width="160px">
          <template #default="scope">
            <p>
              {{scope.row.gmtEnd === undefined? "无": new Date(scope.row.gmtStart).format("yyyy-MM-dd hh:mm")}}
            </p>
          </template>
        </el-table-column>
        <el-table-column prop="gmtEnd" label="领卷结束时间" align="center" width="160px">
          <template #default="scope">
            <p>
              {{scope.row.gmtStart === undefined? "无": new Date(scope.row.gmtEnd).format("yyyy-MM-dd hh:mm")}}
            </p>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="操作" width="200%" align="center">
          <template #default="scope">
            <el-button :type="scope.row.status==0?'primary':(scope.row.gmtEnd<Date.now()?'warning':'danger')" plain
              @click="activation(scope.row)">
              {{scope.row.status==0?'激活':(scope.row.gmtEnd<Date.now()?'过期':'冻结')}} </el-button>
                <el-button type="primary" @click="handleDelete(scope.row)" v-permission='"promotion:coupon:list"'>查看</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <paging-list @Change="giterList" :listdata="listdata"></paging-list>

    <!-- 对话框 -->
    <el-dialog v-model="centerDialogVisible" :title="title" width="50%" align-center>
      <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px" class="demo-ruleForm" status-icon
        :disabled="title == '查看'? true:false">
        <el-form-item label="优惠卷名称" prop="title" label-width="100px">
          <el-input v-model="ruleForm.title" autocomplete="off" />
        </el-form-item>
        <el-form-item label="优惠卷类型" prop="type" label-width="100px">
          <el-select v-model="ruleForm.type" placeholder="请选择优惠卷类型">
            <el-option v-for="item in couponTypeMap.slice(0,2)" :key="item.value" :label="item.name"
              :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="介绍" label-width="100px" prop="description">
          <el-input v-model="ruleForm.description" autocomplete="off" />
        </el-form-item>
        <el-form-item label="优惠券数量" label-width="100px" prop="total">
          <el-input v-model="ruleForm.total" placeholder="请输入优惠券数量"><template #append>张</template></el-input>
        </el-form-item>
        <el-form-item label="每人限领" label-width="100px" prop="limit">
          <el-input v-model="ruleForm.limit" placeholder="请输入每人限领"><template #append>张</template></el-input>
        </el-form-item>
        <el-form-item label="优惠金额" label-width="100px" prop="discount">
          <el-input v-model="ruleForm.discount" placeholder="请输入优惠金额"><template #append>元</template></el-input>
        </el-form-item>
        <el-form-item label="最低消费" label-width="100px" prop="min">
          <el-input v-model="ruleForm.min" placeholder="请输入最低消费"><template #append>元</template></el-input>
        </el-form-item>
        <el-form-item label="优惠券状态" label-width="100px" prop="status">
          <el-select v-model="ruleForm.status" placeholder="请选择优惠卷状态">
            <el-option v-for="item in couponStatusMap.slice(0,2)" :key="item.value" :label="item.name"
              :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="有效期" label-width="100px">
          <el-radio-group v-model="tabPosition" class="radio-group">
            <el-radio-button :label="0">领券相对天数</el-radio-button>
            <el-radio-button :label="1">指定绝对时间</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label-width="100px">
          <el-config-provider :locale="zhCn">
            <el-input v-model.trim="ruleForm.days" v-if="tabPosition == 0">
              <template #append>天</template>
            </el-input>
            <div v-else>
              <el-date-picker  value-format="x" v-model="ruleForm.gmtStart" type="datetime" placeholder="选择开始日期" /> 至
              <el-date-picker   value-format="x" v-model="ruleForm.gmtEnd" type="datetime" placeholder="选择结束日期" />
            </div>
          </el-config-provider>
        </el-form-item>
        <el-form-item label="商品限制范围">
          <el-radio-group v-model="goodsLimitChecked">
            <el-radio-button :label="0">全场通用</el-radio-button>
            <el-radio-button :label="1">指定分类</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="优惠类目" label-width="100px" v-if="goodsLimitChecked==1">
          <el-cascader :options="categoryTreeData.getlist" v-model="ruleForm.categoryId" :props="categoryProps"
            clearable placeholder="优惠类目" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="centerDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="title=='查看'?centerDialogVisible = false:submitForm(ruleFormRef)">确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue'
import { Search, Plus, Download } from '@element-plus/icons-vue'
import { post } from "@/utils/request";
import { ElMessage } from 'element-plus';
import type { FormInstance, FormRules } from 'element-plus'
import zhCn from 'element-plus/lib/locale/lang/zh-cn'//国际语言
import { Pagesourcecode } from "#/index";
import XLXS from "xlsx";
import FileSaver from "file-saver";

let title = ref('创建')
let listdata = reactive(new Pagesourcecode()) //分页数据
// 分页
const giterList = (e: { page: number; limit: number; total: number; flog: { valueOf: () => boolean; }; targetAdminId?: undefined; }) => { //获取下一页的数据并赋值
  listdata = e
  discountcouponlist()
}
const databinding = reactive({ title: '', type: '', status: '' }) //查找绑定的数据
const couponTypeMap = reactive([{ value: 1, name: '满减卷' }, { value: 2, name: '立减卷' }, { value:null, name: '全部' }])
const couponStatusMap = reactive([{ value: 0, name: '下架' }, { value: 1, name: '正常' }, { value: -1, name: '已过期' }, { value: null, name: '全部' }])
const tabledata = reactive({ list: [] as string[] }) //优惠卷表格数据
const centerDialogVisible = ref(false)
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
  title: "",
  type: 1,
  description: "",
  total: 0,
  limit: 0,
  discount: 0,
  min: 0,
  status: 1,
  days: "",
  gmtStart: "",
  gmtEnd: "",
  categoryId: "",
})
const rules = reactive<FormRules>({
  // 优惠券名称验证
  title: [{ required: true, message: '请输入优惠券名称', trigger: 'blur' }],
  // 优惠券类型验证
  type: [{ required: true, message: '请选择类型', trigger: 'change', }],
  // 优惠券数量验证
  total: [{ required: true, message: '请输入优惠券数量', trigger: 'change' }],
  // 每人限领验证
  limit: [{ required: true, message: '请输入每人限领', trigger: 'change'}],
  // 优惠金额验证
  discount: [{ required: true, message: '请输入优惠金额', trigger: 'change'}],
  // 最低消费验证
  min: [{ required: true, message: '请输入最低消费金额', trigger: 'change'}],
  // 优惠券状态验证
  status: [{ required: true, message: '请选择优惠卷的状态', trigger: 'change', }]
})
const tabPosition = ref(0)
const goodsLimitChecked = ref(1)
const categoryTreeData = reactive({ getlist: [] }) //优惠类目
const categoryProps = reactive({
  label: "title",
  children: "childrenList",
  value: "id",
  checkStrictly: true,
  emitPath: false
})


const submitForm = async (formEl: FormInstance | undefined) => { //添加
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (ruleForm.limit > ruleForm.total) {
        return  ElMessage.warning("优惠卷数量不能小于每人限领的数量")
      } else if (ruleForm.gmtStart > ruleForm.gmtEnd) {
        return ElMessage.warning('开始时间不能大于过期时间')
      } else if (ruleForm.discount < ruleForm.min) {
        return  ElMessage.warning('优惠的金额不能小于最低消费金额')
      }
      let data = {
        _gp: 'admin.coupon',
        _mt: 'create',
        ...ruleForm
      }
      post(data).then(res => {
        console.log(res);
        let { errno, errmsg } = res
        if (200 == errno) {
          discountcouponlist()
          ElMessage.success('创建成功')
          centerDialogVisible.value = false
        }
      })
    } else {
      console.log('error submit!', fields)
    }
  })
}

function offeraddition() { //打开弹出框
  title.value = "创建"
  centerDialogVisible.value = true
  ruleForm.title = '',
    ruleForm.categoryId = '',
    ruleForm.days = '',
    ruleForm.description = '',
    ruleForm.discount = 0,
    ruleForm.gmtEnd = '',
    ruleForm.gmtStart = '',
    ruleForm.limit = 0,
    ruleForm.min = 0,
    ruleForm.status = '',
    ruleForm.total = 0,
    ruleForm.type = 1
}


// 查看
function handleDelete(params: { id: string, categoryId: string, days: string, gmtStart: number, gmtEnd: number }) {
  title.value = "查看"
  Object.assign(ruleForm, params)
  if (!params.categoryId) {
    goodsLimitChecked.value = 0 //全场通用
  } else {
    goodsLimitChecked.value = 1 //指定分类
  }
  // 有效期
  if (params.days) {
    tabPosition.value = 0
  } else if (params.gmtStart) {
    tabPosition.value = 1
  }

  if (params.gmtEnd < Date.now()) {
    ruleForm.status = "已过期"
  }
  centerDialogVisible.value = true
}

// 初始化数据
function discountcouponlist() {
  let data = {
    _gp: 'admin.coupon',
    _mt: 'list',
    title: listdata.title,
    type: listdata.type,
    status: listdata.status,
    pageNo: listdata.page,
    limit: listdata.limit
  }
  post(data).then(res => {
    console.log(res);
    let { data } = res
    tabledata.list.length = 0
    tabledata.list.push(...data.items)
    listdata.total = data.total
  })
}
discountcouponlist()

// 初始化优惠类目
function categoryTree() {
  let data = {
    _gp: 'admin.category',
    _mt: 'categoryTree',
  }
  post(data).then(res => {
    let { errno, errmsg } = res
    if (200 == errno) {
      categoryTreeData.getlist.length = 0
      categoryTreeData.getlist.push(...res.data)
    } else {
      ElMessage.warning(errmsg)
    }
  })
}
categoryTree()

// 激活
function activation(params: { id: string, gmtEnd: number, status: string }) {
  if (params.gmtEnd < Date.now()) {
    ElMessage.warning('已过期，建议删除！')
    return
  }
  let data = {
    _gp: 'admin.coupon',
    _mt: 'updateCouponStatus',
    id: params.id,
    status: params.status ? '0' : '1'
  }
  post(data).then(res => {
    console.log(res);
    let { errno, errmsg } = res
    if (200 == errno) {
      ElMessage.success(params.status ? '下架成功' : '激活成功')
      discountcouponlist()
    }
  })
}

// 查找
function couponsearch() {
  listdata.title = databinding.title
  listdata.type = databinding.type
  listdata.status = databinding.status
  discountcouponlist()
}

//导出文件
const exportClick = () => {
  // 导出文件名
  const filename = "导出.xlsx";
  // 导出表格加id,通过id获取要导出的表单
  const wb = XLXS.utils.table_to_book(document.getElementById("table"));
  const wbout = XLXS.write(wb, {
    bookType: "xlsx",
    bookSST: true,
    type: "array",
  });
  try {
    FileSaver.saveAs(
      new Blob([wbout], {
        type: "application/octet-stream",
      }),
      filename
    );
  } catch (e) {
    console.log(e);
  }
  return wbout;
};

</script>


<style lang="less" scoped>
.dialog-footer button:first-child {
  margin-right: 10px;
}
</style>